<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="180px" size="small">
      <el-form-item label="渠道名" prop="name">
        <el-input v-model="form.name" placeholder="请输入渠道名" />
      </el-form-item>
      <el-form-item label="选择短剧" prop="video_id">
        <YxhyTableDialogSelect
          :btn-text="`选择短剧`"
          :table-key="`library_id`"
          :table-name="`title`"
          :detail-data="(isEdit || isCamouflage) ? formDetail : null"
          :detail-id-key="`video_id`"
          :columns="columnsSelectLibrary"
          :query-params="queryParamsSelectLibrary"
          :query-columns="queryColumnsSelectLibrary"
          :request-fn="queryNonSortLibrary"
          @selectResult="handleSelectResultLibrary"
        />
      </el-form-item>
      <el-form-item label="跳转剧集" prop="vide_series_id">
        <YxhySelect :value.sync="form.vide_series_id" :columns="episodeColumns" />
      </el-form-item>
      <el-form-item label="关联小程序" prop="applet">
        <YxhyTableDialogSelect
          :btn-text="`选择小程序`"
          :table-key="`product_id`"
          :table-name="`product_name`"
          :detail-data="isEdit ? formDetail : null"
          :detail-id-key="`applet`"
          :columns="columnsSelectMp"
          :query-params="queryParamsSelectMp"
          :query-columns="queryColumnsSelectMp"
          :request-fn="queryListNonSortMp"
          @selectResult="handleSelectResultMp"
        />
      </el-form-item>
      <el-form-item label="投放平台" prop="delivery_platform">
        <YxhySelect :value.sync="form.delivery_platform" :columns="platformColumns" />
      </el-form-item>
      <el-form-item label="充值模板" prop="applet">
        <YxhyTableDialogSelect
          :btn-text="`选择充值模板`"
          :add-page-router="`/config/template/list`"
          :should-add-button="true"
          :table-key="`id`"
          :table-name="`name`"
          :detail-data="isEdit ? formDetail : null"
          :detail-id-key="`pay_temp_id`"
          :columns="columnsSelectTemplate"
          :query-params="queryParamsSelectTemplate"
          :static-query-params="staticQueryParamsSelectTemplate"
          :query-columns="queryColumnsSelectTemplate"
          :request-fn="queryListTemplate"
          @selectResult="handleSelectResultTemplate"
        />
      </el-form-item>
      <el-form-item label="起始收费集" prop="pay_start_episode">
        <YxhySelect :value.sync="form.pay_start_episode" :columns="episodeColumns" />
      </el-form-item>
      <el-form-item label="单集价格" prop="pay_coin">
        <el-input v-model="form.pay_coin" type="number" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="回传配置" prop="report_config_id">
        <YxhyTableDialogSelect
          :btn-text="`选择回传配置`"
          :add-page-router="`/config/channelPostBack/add`"
          :should-add-button="true"
          :table-key="`id`"
          :table-name="`name`"
          :detail-data="isEdit ? formDetail : null"
          :detail-id-key="`report_config_id`"
          :columns="columnsSelectPostBack"
          :query-params="queryParamsSelectPostBack"
          :query-columns="queryColumnsSelectPostBack"
          :static-query-params="{all: 1}"
          :request-fn="queryPageChannelList"
          @selectResult="handleSelectResultPostBack"
        />
      </el-form-item>
<!--      <el-form-item label="激励视频可领取解锁次数" prop="collect_unlock">
        <el-input v-model="form.collect_unlock" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="激励视频广告解锁集数" prop="adv_unlock">
        <el-input v-model="form.adv_unlock" placeholder="请输入" />
      </el-form-item>-->
    </el-form>

    <div class="flex ai-center jc-center pb-50">
      <el-button type="info" plain @click="handleBack">返回</el-button>
      <el-button type="success" @click="handleVerify">{{ isEdit ? '修改' : '添加' }}</el-button>
    </div>
  </div>
</template>

<script>
import { queryPageChannelList } from '@/api/config/channelPostBack.js'
import {
  columnsSelectLibrary,
  columnsSelectMp,
  columnsSelectTemplate,
  columnsSelectPostBack
} from '@/views/config/channelData/Ds'
import { queryListLibrary, queryNonSortLibrary, queryTotalEpisode } from '@/api/video/library'
import { queryListMp, queryListNonSortMp } from '@/api/miniProgram/mp'
import { queryListTemplate } from '@/api/config/template'
import { addChannelData, editChannelData, queryChannelDataDetail } from '@/api/config/channelData'

export default {
  name: 'ChannelPostBackAdd',
  data() {
    return {
      // 表单参数
      form: {
        name: undefined,
        video_id: undefined, // 短剧Id
        vide_series_id: undefined, // 剧集Id
        applet: undefined, // 小程序Id
        delivery_platform: 1, // 投放平台Id
        pay_temp_id: undefined, // 充值模板Id
        pay_start_episode: undefined, // 起始收费集数
        pay_coin: undefined, // 单集价格
        report_config_id: undefined, // 回传配置Id
        collect_unlock: undefined, // 激励视频可领取解锁次数
        adv_unlock: undefined // 激励视频广告解锁集数
      },
      formDetail: {},
      isCamouflage: false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入渠道名', trigger: ['blur', 'change'] }
        ],
        video_id: [
          { required: true, message: '请选择短剧', trigger: ['blur', 'change'] }
        ],
        vide_series_id: [
          { required: true, message: '请选择跳转剧集', trigger: ['blur', 'change'] }
        ],
        applet: [
          { required: true, message: '请选择关联小程序', trigger: ['blur', 'change'] }
        ],
        report_config_id: [
          { required: true, message: '请选择回传配置', trigger: ['blur', 'change'] }
        ]
        // pay_min_price: {
        //   validator: (rule, value, callback) => {
        //     if (value && Number(value) < Number(this.form.first_pay_min_price)) callback(new Error('需要大于等于首充最低回传金额'))
        //     else callback()
        //   },
        //   trigger: ['blur', 'change']
        // }
      },

      // 选择短剧
      queryParamsSelectLibrary: {
        library_id_search: undefined,
        title_search: undefined
      },
      queryColumnsSelectLibrary: [
        {
          label: '',
          placeholder: '请输入短剧ID',
          type: 'input',
          param: 'library_id_search'
        }, {
          label: '',
          placeholder: '请输入短剧名称',
          type: 'input',
          param: 'title_search'
        }
      ],
      columnsSelectLibrary,
      queryListLibrary,
      queryNonSortLibrary,

      // 跳转剧集
      episodeColumns: [],

      // 关联小程序
      queryParamsSelectMp: {
        product_id_search: undefined,
        product_name_search: undefined
      },
      queryColumnsSelectMp: [
        {
          label: '',
          placeholder: '请输入id',
          type: 'input',
          param: 'product_id_search'
        }, {
          label: '',
          placeholder: '请输入小程序名称',
          type: 'input',
          param: 'product_name_search'
        }
      ],
      columnsSelectMp,
      queryListMp,
      queryListNonSortMp,

      // 投放平台
      platformColumns: [
        {
          value: 1,
          label: '抖音'
        },
        {
          value: 2,
          label: 'APP'
        },
        {
          value: 999,
          label: '其它'
        }
      ],

      // 充值模板
      queryParamsSelectTemplate: {
        name: undefined
      },
      staticQueryParamsSelectTemplate: {
        all: 1,
        flag: 1 // 有效
      },
      queryColumnsSelectTemplate: [
        {
          label: '',
          placeholder: '请输入充值模板名称',
          type: 'input',
          param: 'name'
        }
      ],
      columnsSelectTemplate,
      queryListTemplate,

      // 回传配置
      queryParamsSelectPostBack: {
        name: undefined
      },
      queryColumnsSelectPostBack: [
        {
          label: '',
          placeholder: '请输入规则名称',
          type: 'input',
          param: 'name'
        }
      ],
      columnsSelectPostBack,
      queryPageChannelList
    }
  },
  computed: {
    isEdit() {
      return ![undefined, ''].includes(this.form.id)
    }
  },
  created() {
    const { id } = this.$route.query
    this.form.id = id

    this.queryChannelDataDetailFn()
  },
  mounted() {
    const { libraryId } = this.$route.query

    if (libraryId) this.setSailVideo(libraryId)
  },
  methods: {
    async queryChannelDataDetailFn() {
      if (!this.form.id) return

      const data = await queryChannelDataDetail({
        id: this.form.id
      })
      data.pay_start_episode = data.pay_start_episode || undefined
      data.pay_coin = data.pay_coin || undefined

      this.form = data
      this.formDetail = data

      await this.queryTotalEpisodeFn()
    },
    // 从短剧列表跳转，设置选中短剧
    setSailVideo(libraryId) {
      libraryId = Number(libraryId)
      this.form.video_id = libraryId
      this.formDetail.video_id = libraryId
      this.isCamouflage = true
      this.queryTotalEpisodeFn()
    },
    /** 接收短剧选择 */
    handleSelectResultLibrary(rows) {
      const library_id_str = rows.map(item => item.library_id).toString()
      this.form.video_id = library_id_str

      if (this.form.video_id) {
        this.form.vide_series_id = undefined
        this.queryTotalEpisodeFn()
      } else {
        this.episodeColumns = []
        this.form.episode_id = undefined
      }
    },
    /** 根据已选择短剧，查询剧集库 */
    async queryTotalEpisodeFn() {
      const res = await queryTotalEpisode({
        library_id: this.form.video_id
      })
      const arr = res.map(e => {
        const { episode_id, episode } = e
        return { value: episode_id, label: `第${episode}集`, episode: episode }
      })
      this.episodeColumns = arr

      if (this.form.pay_start_episode) {
        this.form.pay_start_episode = arr.find(f => f.episode == this.form.pay_start_episode).value
      }
    },
    /** 接收小程序选择 */
    handleSelectResultMp(rows) {
      const is_str = rows.map(item => item.product_id).toString()
      this.form.applet = is_str
    },
    /** 接收充值模板选择 */
    handleSelectResultTemplate(rows) {
      const is_str = rows.map(item => item.id).toString()
      this.form.pay_temp_id = is_str
    },
    /** 接收回传配置选择 */
    handleSelectResultPostBack(rows) {
      const is_str = rows.map(item => item.id).toString()
      this.form.report_config_id = is_str
    },
    async handleBack() {
      await this.$tab.closePage({
        path: '/config/channelData/add', name: 'ChannelDataAdd'
      })
      await this.$tab.refreshPage({ path: '/config/channelData/list', name: 'ChannelDataList' })
      await this.$tab.openPage('渠道列表', '/config/channelData/list')
    },
    handleVerify() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.form.collect_unlock = this.form.collect_unlock || undefined
          this.form.adv_unlock = this.form.adv_unlock || undefined
          this.form.pay_start_episode = this.episodeColumns.find(f => f.value == this.form.pay_start_episode)?.episode
          if (this.isEdit) {
            editChannelData(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.handleBack()
            })
          } else {
            addChannelData(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.handleBack()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.report_type_nav {
  ::v-deep .el-radio {
    margin-bottom: 10px;
  }
}

.el-form {
  padding: 20px;
  margin: 20px;
  border: 1px solid #dddddd;
}
</style>
